<template>
  <div class="template-process-page">
    <div class="page-container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>智能工具</el-breadcrumb-item>
        <el-breadcrumb-item>TXT解析工具</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="page-header">
        <h2 class="page-title">TXT解析工具</h2>
        <p class="page-description">
          将病历TXT文本或文件结构化处理，提取键值，匹配模板，生成规范的JSON数据
        </p>
      </div>

      <!-- 服务状态检查 -->
      <el-alert
        v-if="serviceStatus === 'error'"
        title="后端服务连接失败"
        type="error"
        description="无法连接到后端服务，请确保服务已启动"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #default>
          <div>
            无法连接到后端服务，请确保服务已启动并且地址配置正确
            <div class="mt-2">
              <el-button size="small" type="primary" @click="checkServiceStatus" :loading="checkingService" style="margin-right: 10px;">
                重试连接
              </el-button>
              <el-button size="small" type="info" @click="openBackendUrl" style="margin-right: 10px;">
                直接访问后端
              </el-button>
              <el-button size="small" type="success" @click="testTemplateAPI">
                测试模板API
              </el-button>
            </div>
            <div class="mt-2 text-gray">
              当前后端地址: {{ apiService.apiClient.defaults.baseURL }}
            </div>
            
            <!-- API测试面板 -->
            <div class="mt-4">
              <el-collapse>
                <el-collapse-item title="API测试工具" name="1">
                  <div class="api-test-panel">
                    <el-form>
                      <el-form-item label="API路径">
                        <el-input v-model="testApiPath" placeholder="/api/heart/healthy"></el-input>
                      </el-form-item>
                      <el-form-item label="请求方法">
                        <el-radio-group v-model="testApiMethod">
                          <el-radio label="GET">GET</el-radio>
                          <el-radio label="POST">POST</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="请求体" v-if="testApiMethod === 'POST'">
                        <el-input
                          type="textarea"
                          :rows="3"
                          placeholder="{}"
                          v-model="testApiBody"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="sendTestRequest" :loading="testingApi">
                          发送请求
                        </el-button>
                      </el-form-item>
                    </el-form>
                    
                    <div v-if="testApiResult" class="mt-3">
                      <h4>响应结果:</h4>
                      <pre class="api-result">{{ testApiResult }}</pre>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </template>
      </el-alert>

      <!-- 引入病历解析工具组件 -->
      <MedicalRecordParser />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import MedicalRecordParser from '../components/MedicalRecordParser.vue'
import apiService from '../services/api'

const serviceStatus = ref('checking') // checking, ok, error
const checkingService = ref(false)

// API测试相关
const testApiPath = ref('/heart/healthy')
const testApiMethod = ref('GET')
const testApiBody = ref('{}')
const testApiResult = ref('')
const testingApi = ref(false)

// 发送测试请求
const sendTestRequest = async () => {
  testingApi.value = true
  try {
    let response
    const url = testApiPath.value
    
    if (testApiMethod.value === 'GET') {
      response = await apiService.apiClient.get(url)
    } else {
      let body = {}
      try {
        body = JSON.parse(testApiBody.value)
      } catch (e) {
        ElMessage.warning('请求体JSON格式不正确，将使用空对象')
      }
      response = await apiService.apiClient.post(url, body)
    }
    
    testApiResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('请求成功')
  } catch (error) {
    console.error('测试请求失败:', error)
    
    if (error.response) {
      testApiResult.value = JSON.stringify({
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      }, null, 2)
    } else if (error.request) {
      testApiResult.value = '请求已发送但没有收到响应，可能是CORS问题或服务器未运行'
    } else {
      testApiResult.value = error.message || '未知错误'
    }
    
    ElMessage.error('请求失败')
  } finally {
    testingApi.value = false
  }
}

// 检查后端服务是否正常运行
const checkServiceStatus = async () => {
  checkingService.value = true
  serviceStatus.value = 'checking'
  
  try {
    console.log('开始检查后端服务状态')
    await apiService.healthService.checkHealthAll()
    console.log('后端服务正常运行')
    serviceStatus.value = 'ok'
    ElMessage.success('后端服务连接正常')
  } catch (error) {
    console.error('后端服务连接失败:', error)
    serviceStatus.value = 'error'
    ElMessage.error('无法连接到后端服务，请确保服务已启动')
  } finally {
    checkingService.value = false
  }
}

// 直接在浏览器中打开后端URL
const openBackendUrl = () => {
  const baseUrl = apiService.apiClient.defaults.baseURL
  window.open(baseUrl, '_blank')
}

// 测试模板API
const testTemplateAPI = async () => {
  testApiPath.value = '/api/template/process/text'
  testApiMethod.value = 'POST'
  testApiBody.value = JSON.stringify({
    textContent: '患者姓名：张三\n性别：男\n年龄：45岁\n主诉：头痛3天'
  }, null, 2)
  await sendTestRequest()
}

// 组件挂载时检查服务状态
onMounted(() => {
  checkServiceStatus()
})
</script>

<style scoped>
.template-process-page {
  padding: 0;
  width: 100%;
}

.page-container {
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
  padding: 0 30px;
}

.page-header {
  margin: 20px 0 30px;
  width: 100%;
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.page-description {
  color: #606266;
  font-size: 16px;
}

.mt-2 {
  margin-top: 8px;
}

.text-gray {
  color: #909399;
  font-size: 14px;
}

.api-test-panel {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.api-result {
  padding: 10px;
  background-color: #f1f1f1;
  border-radius: 4px;
  overflow: auto;
  max-height: 300px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-word;
}

.text-gray {
  color: #606266;
}

.mt-2 {
  margin-top: 8px;
}

.mt-3 {
  margin-top: 12px;
}

.mt-4 {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style> 